#include <my_header.h>

#define TIMES 1000000

typedef struct share_value
{
    int sum;
    pthread_mutex_t mLock;
}share_value_t;

void * threadFunc(void * arg)
{
    /* 锁传入 */

    share_value_t *pshareValue = (share_value_t*)arg;
    printf("I am child thread\n");

    for(int i = 0;i<TIMES;i++)
    {
        pthread_mutex_lock(&pshareValue->mLock);
        pshareValue->sum++;
        pthread_mutex_unlock(&pshareValue->mLock);

    }
    printf("child thread stop \n");
    return NULL;
}

/*验证线程共享堆空间 */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);

    /* 时间初始化 */
    struct timeval beginTime,endTime;
    gettimeofday(&beginTime,NULL);
    /* 锁的初始化 */
    share_value_t shareValue;
    shareValue.sum = 0;
    pthread_mutex_init(&shareValue.mLock,NULL);

    pthread_t tid;
    int ret = pthread_create(&tid,NULL,threadFunc,&shareValue);
    ERROR_CHECK(ret,-1,"pthread_create");
    printf("I am main thread\n");

    for(int i = 0;i<TIMES;i++)
    {
        pthread_mutex_lock(&shareValue.mLock);
        shareValue.sum++;
        pthread_mutex_unlock(&shareValue.mLock);
    }
    printf("main thread stop\n");

    pthread_join(tid,NULL);

    printf("all over,shareValue.value = %d \n",shareValue.sum);

    /* 销毁锁 */
    pthread_mutex_destroy(&shareValue.mLock);

    gettimeofday(&endTime,NULL);

    printf("time: %ld us \n",endTime.tv_usec - beginTime.tv_usec +
          (endTime.tv_sec - beginTime.tv_sec)*1000000);
    return 0;
}

